<?php

namespace app\yy\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\yy\model\IpRecord;
use app\yy\model\IpRequestRecord;
use app\yy\model\IpStatistics as IpStatModel;
use app\yy\model\Website as WebModel;
use app\yy\model\Domain as DoModel;

class Flowrate extends Admin
{

    public function getWhereMap()
    {
        $map = $this->getMap();
        $where = [];
        if ($map) {
            $domain_id = DoModel::where($map)->column('id');
            if ($domain_id) {
                $where[] = [
                    'domain_id',
                    'in',
                    $domain_id
                ];
            } else {
                $where[] = [
                    'domain_id',
                    '<',
                    0
                ];
            }
        }
        return $where;
    }

    public function index()
    {
        // 获取查询条件
        $map = $this->getWhereMap();

        // halt('重新优化中');

        // 获取昨天的时间戳
        $yesterday = strtotime(date('Y-m-d', strtotime('-1 day')));
        $statistics = IpStatModel::where('date', '>=', $yesterday)
            ->field('sum(ip_num) ip_num,sum(pv_num) pv_num,is_mobile,date')
            ->where($map)
            ->group('date,is_mobile')
            ->order('date DESC')
            ->select()->toArray();

        $yesterday_ip = IpRecord::where('date_added','>',date('Y-m-d', strtotime('-1 day')))
            ->where('date_added','<', date('Y-m-d'))
            ->where('is_mobile',1)
            ->group('ip_address')
            ->count();
        $today_ip = IpRecord::where('date_added','>', date('Y-m-d'))
            ->where('is_mobile',1)
            ->group('ip_address')
            ->count();
        $statistics_list = [
            'today' => [
                'ip_num' => 0,
                'pv_num' => 0,
                'move_ip_num' => 0,
                'move_pv_num' => 0,
                'pc_ip_num' => 0,
                'pc_pv_num' => 0,
                'move_all_ip_num' => $today_ip
            ],
            'yesterday' => [
                'ip_num' => 0,
                'pv_num' => 0,
                'move_ip_num' => 0,
                'move_pv_num' => 0,
                'pc_ip_num' => 0,
                'pc_pv_num' => 0,
                'move_all_ip_num' => $yesterday_ip,
            ]
        ];
        foreach ($statistics as $statistic) {
            if ($statistic['date'] == strtotime(date('Y-m-d', strtotime('-1 day')))) {
                $statistics_list['yesterday']['ip_num'] += $statistic['ip_num'];
                $statistics_list['yesterday']['pv_num'] += $statistic['pv_num'];
                if ($statistic['is_mobile']){
                    $statistics_list['yesterday']['move_ip_num'] += $statistic['ip_num'];
                    $statistics_list['yesterday']['move_pv_num'] += $statistic['pv_num'];
                }else{
                    $statistics_list['yesterday']['pc_ip_num'] += $statistic['ip_num'];
                    $statistics_list['yesterday']['pc_pv_num'] += $statistic['pv_num'];
                }
            } else {
                $statistics_list['today']['ip_num'] += $statistic['ip_num'];
                $statistics_list['today']['pv_num'] += $statistic['pv_num'];
                if ($statistic['is_mobile']){
                    $statistics_list['today']['move_ip_num'] += $statistic['ip_num'];
                    $statistics_list['today']['move_pv_num'] += $statistic['pv_num'];
                }else{
                    $statistics_list['today']['pc_ip_num'] += $statistic['ip_num'];
                    $statistics_list['today']['pc_pv_num'] += $statistic['pv_num'];
                }
            }
        }

        // 根据域名获取IP数排序
        $domain_list = IpStatModel::where($map)->where('date', '>=', strtotime(date('Y-m-d')))->group('domain_id')->field("sum(ip_num) ip_num_total,domain_id")->order('ip_num_total DESC')->paginate(10);
        $page = $domain_list->render();
        $domain_ids = array_column($domain_list->toArray()['data'], 'domain_id');
        $domains = DoModel::where('id', 'in', $domain_ids)->column('domain', 'id');
        // 获取昨天的时间戳
        $yesterday = strtotime(date('Y-m-d', strtotime('-1 day')));
        $list = IpStatModel::where('domain_id', 'in', $domain_ids)
            ->where('date', '>=', $yesterday)
            ->select();

        $data_list = [];
        foreach ($list as $info) {
            if (!isset($data_list[$info['domain_id']])) {
                $data_list[$info['domain_id']] = [
                    'domain' => $domains[$info['domain_id']] ?? $info['domain_id'],
                    'id' => $info['domain_id'],
                    'today_ip' => 0,
                    'today_pv' => 0,
                    'today_mobile_ip_num' => 0,
                    'today_pc_ip_num' => 0,
                    'today_mobile_pv_num' => 0,
                    'today_pc_pv_num' => 0,
                    'yesterday_ip' => 0,
                    'yesterday_pv' => 0,
                    'yesterday_mobile_ip_num' => 0,
                    'yesterday_pc_ip_num' => 0,
                    'yesterday_mobile_pv_num' => 0,
                    'yesterday_pc_pv_num' => 0
                ];
            }
            if ($info['date'] == $yesterday) {   // 昨天的数据
                $type = 'yesterday_';
            } else {
                $type = 'today_';
            }
            $data_list[$info['domain_id']][$type . 'ip'] += $info['ip_num'];
            $data_list[$info['domain_id']][$type . 'pv'] += $info['pv_num'];
            $data_list[$info['domain_id']][$type . 'mobile_ip_num'] += ($info['is_mobile'] ? $info['ip_num'] : 0);
            $data_list[$info['domain_id']][$type . 'pc_ip_num'] += ($info['is_mobile'] ? 0 : $info['ip_num']);
            $data_list[$info['domain_id']][$type . 'mobile_pv_num'] += ($info['is_mobile'] ? $info['pv_num'] : 0);
            $data_list[$info['domain_id']][$type . 'pc_pv_num'] += ($info['is_mobile'] ? 0 : $info['pv_num']);
        }

        $today_ip = array_column($data_list, 'today_ip');
        array_multisort($today_ip, SORT_DESC, $data_list);
        return ZBuilder::make('table')
            ->setPageTitle('IP统计') // 设置页面标题
            ->setTableName('domain') // 设置数据表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text', 'domain', '网站', 'like']
            ])
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['domain', '域名'],
                ['type', '日期', 'callback', function ($data) {
                    return "今日<br>昨日";
                }, '__data__'],
                ['ip', 'ip数', 'callback', function ($data) {
                    return $data['today_ip'] . "<br>" . $data['yesterday_ip'];
                }, '__data__'],
                ['pv', 'pv数', 'callback', function ($data) {
                    return $data['today_pv'] . "<br>" . $data['yesterday_pv'];
                }, '__data__'],
                // ['mobile_ip_num', '移动端-ip数', 'callback', function ($data){
                //     return $data['today_mobile_ip_num']."<br>".$data['yesterday_mobile_ip_num'];
                // },'__data__'],
                // ['pc_ip_num', 'PC端-ip数', 'callback', function ($data){
                //     return $data['today_pc_ip_num']."<br>".$data['yesterday_pc_ip_num'];
                // },'__data__'],
                // ['mobile_pv_num', '移动端-pv数', 'callback', function ($data){
                //     return $data['today_mobile_pv_num']."<br>".$data['yesterday_mobile_pv_num'];
                // },'__data__'],
                // ['pc_pv_num', 'PC端-pv数', 'callback', function ($data){
                //     return $data['today_pc_pv_num']."<br>".$data['yesterday_pc_pv_num'];
                // },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('detail', ['title' => '详情', 'icon' => 'fa fa-fw fa-map-o', 'href' => url('detail', ['id' => '__id__'])]) // 批量添加右侧按钮
            ->addRightButton('list', ['title' => 'IP列表', 'icon' => 'fa fa-fw fa-indent', 'href' => url('list', ['id' => '__id__'])]) // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page)
            ->setExtraHtmlFile('statistics', 'toolbar_top', ['statistics' => $statistics_list])
            ->setColumnWidth([
                'id' => 40,
                'type' => 40,
                'ip' => 50,
                'pv' => 50,
                'mobile_ip_num' => 50,
                'pc_ip_num' => 50,
                'mobile_pv_num' => 50,
                'pc_pv_num' => 50,
                'right_button' => 60
            ])
            ->fetch(); // 渲染页面
    }

    public function detail($id = '')
    {
        // 单独网站对比
        $yesterday = strtotime(date('Y-m-d', strtotime('-1 day')));
        $list = IpStatModel::where('domain_id', $id)->where('date', '>=', $yesterday)
            ->field("sum(ip_num) ip_num_total,sum(pv_num) pv_num_total,date")
            ->group('date')->order('date DESC')->select()->toArray();
        foreach ($list as &$val) {
            $val['date'] = $val['date'] == $yesterday ? '昨日' : '今日';
        }

        // 设备占比
        $date = $this->request->get('date', '1');
        $where = [];
        $time = strtotime(date('Y-m-d', strtotime('-' . $date . ' day')));
        if ($date == 1) {
            $where = [
                ['date', '>=', $time],
                ['date', '<', strtotime(date('Y-m-d'))],
            ];
        } else {
            $where = [
                ['date', '>=', $time]
            ];
        }
//        halt($where);
        $equ_list = IpStatModel::where('domain_id', $id)
            ->where($where)
            ->field("sum(ip_num) ip_num_total,sum(pv_num) pv_num_total,is_mobile")
            ->group('is_mobile')
            ->order('is_mobile')
            ->select()->toArray();

        foreach ($equ_list as &$equ) {
            $equ['equ'] = $equ['is_mobile'] ? '移动端' : 'PC端';
        }
        // 地区排行
        $address_list = IpStatModel::where('domain_id', $id)
            ->where($where)
            ->field("sum(ip_num) ip_num_total,sum(pv_num) pv_num_total,country_code,continent_code")
            ->group('country_code,continent_code')
            ->order('ip_num_total DESC')
            ->limit(15)
            ->select()->toArray();
        $total = array_sum(array_column($address_list, 'ip_num_total'));
        foreach ($address_list as &$address) {
            $address['scale'] = sprintf("%.2f", ($address['ip_num_total'] / $total) * 100) . '%';
        }

        $this->assign('date', $date);
        $this->assign('list', $list);
        $this->assign('equ_list', $equ_list);
        $this->assign('address_list', $address_list);

        return $this->fetch('detail');
    }

    public function list($id = '')
    {
        $map = $this->getMap();
        if (!$map) {
            $map = [
                ['date_added', 'between time', [date('Y-m-d'), date('Y-m-d 23:59:59')]]
            ];
        }
        // 获取网站的ip列表
        $ip_list = IpRecord::where('domain_id', $id)->where($map)->order('date_added DESC')->paginate();
        $ipIds = array_column($ip_list->toArray()['data'], 'id');
        $ip_records = IpRequestRecord::where('yy_ip_record_id', 'in', $ipIds)->group('yy_ip_record_id')->order('date_added')->column('http_request', 'yy_ip_record_id');

        foreach ($ip_list as &$val) {
            $val['http_request'] = $ip_records[$val['id']] ?? '';
            $val['address'] = $val['country_code'] . ' ' . $val['continent_code'];
            $val['equipment'] = $val['is_mobile'] ? '移动端' : 'PC端';
        }

        return ZBuilder::make('table')
            ->setPageTitle('IP列表') // 设置页面标题
            ->setTableName('ip_record') // 设置数据表名
            ->hideCheckbox()
            ->addTimeFilter('date_added', date('Y-m-d') . ',' . date('Y-m-d'))
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['date_added', '访问时间'],
                ['address', '地址'],
                ['ip_address', 'IP'],
                ['equipment', '设备'],
                ['http_user_agent', '浏览器'],
                ['http_referer', '来源'],
                ['http_request', '入口页'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('history', ['title' => 'IP浏览列表', 'icon' => 'fa fa-fw fa-map-o', 'href' => url('history', ['id' => '__id__'])], ['area' => ['800px', '90%']])
            ->setRowList($ip_list) // 设置表格数据
            ->setColumnWidth([
                'id' => 40,
                'equipment' => 40,
                'ip_address' => 80,
                'http_referer' => 150,
                'http_request' => 150,
                'right_button' => 30
            ])
            ->fetch(); // 渲染页面
    }

    public function history($id)
    {
        $ip_records = IpRequestRecord::where('yy_ip_record_id', $id)->order('date_added DESC')->paginate();
        return ZBuilder::make('table')
            ->setPageTitle('IP浏览列表') // 设置页面标题
            ->setTableName('ip_request_record') // 设置数据表名
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['date_added', '访问时间'],
                ['http_request', '页面地址'],
            ])->setRowList($ip_records) // 设置表格数据
            ->setColumnWidth([
                'id' => 40,
                'date_added' => 80
            ])
            ->fetch(); // 渲染页面

    }
}